package org.jsola.contract.common;

import org.jsola.contract.exception.ContractException;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.MessageFormat;

/**
 * @author JanusMix
 */
public class FileHelper {

    /**
     * description 获取文件字节流
     *
     * @param filePath {@link String} 文件路径
     * @return byte[]
     * {@link java.lang.reflect.Array} 节流流
     **/
    public static byte[] getFileBytes(String filePath) throws ContractException {
        File file = new File(filePath);
        FileInputStream fis = null;
        byte[] buffer;

        try {
            fis = new FileInputStream(file);
            buffer = new byte[(int) file.length()];
            fis.read(buffer);
        } catch (Exception e) {
            throw new ContractException(
                    MessageFormat.format("获取文件字节流异常：{0}", e.getMessage()));
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    throw new ContractException(
                            MessageFormat.format("关闭字节流异常：{0}", e.getMessage()));
                }
            }
        }
        return buffer;
    }

    /**
     * description 文件字节流保存为本地文件
     *
     * @param bytes       {@link java.lang.reflect.Array} 文件字节流
     * @param dstFilePath {@link String} 文件路径
     **/
    public static void saveFileByStream(byte[] bytes, String dstFilePath)
            throws ContractException {

        BufferedOutputStream bos = null;
        File dstFile = new File(dstFilePath);
        //文件目录
        File directory = new File(dstFile.getParent());
        if (!directory.exists() && directory.isDirectory()) {
            directory.mkdirs();
        }

        try {
            bos = new BufferedOutputStream(new FileOutputStream(dstFile));
            bos.write(bytes);
            bos.flush();
        } catch (Exception e) {
            throw new ContractException(
                    MessageFormat.format("文件字节流保存为本地文件异常：{0}", e.getMessage()));
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    throw new ContractException(
                            MessageFormat.format("关闭文件字节流异常：{0}", e.getMessage()));
                }
            }
        }
    }

    /**
     * 下载文件
     *
     * @param urlStr 文件地址
     * @param outPath 文件输出路径
     */
    public static void downloadFile(String urlStr, String outPath) {
        try {
            // 构造URL
            URL url = new URL(urlStr);
            // 打开连接
            URLConnection con = url.openConnection();
            // 输入流
            InputStream is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            OutputStream os = new FileOutputStream(outPath);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            os.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
